//
//  ViewController3.swift
//  NetEaseBUFF
//
//  Created by QFX on 2023/10/27.
//
import SnapKit
import UIKit
import Alamofire
import MJRefresh
import SwiftyJSON
import SDWebImage
import MBProgressHUD

class ViewController3: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return list.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cellIdentifier = "dataCollectionCell"
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! dataCollectionCell
        
 
        let row = indexPath.row
        let item:JSON = self.list[row];
        let name = item["name"].stringValue
        let sell_min_price = item["sell_min_price"].stringValue
        let sell_num = item["sell_num"].int
        let goods_info = item["goods_info"].dictionary
        let icon_url = goods_info?["icon_url"]?.stringValue
        let info = goods_info?["info"]?.dictionary
        let tags = info?["tags"]?.dictionary
        let exterior_localized_name = tags?["exterior"]?["localized_name"].stringValue
        let quality_localized_name = tags?["quality"]?["localized_name"].stringValue
        let rarity = tags?["rarity"]?["localized_name"].stringValue
        
        cell.saleLabel.text = "" /*String(format: "%d", sell_num ?? 0) + "件在售";*/
        cell.priceLabel.text = "￥\(sell_min_price)";
        cell.nameLabel.text = name;
        cell.tipLabel.text = exterior_localized_name == nil ? (rarity != nil ? rarity : exterior_localized_name) : exterior_localized_name;
        cell.dataImageView.sd_setImage(with: URL.init(string: icon_url ?? ""))
        cell.tip1View.isHidden = exterior_localized_name == nil && rarity == nil
        cell.tip2View.isHidden = quality_localized_name == nil
        cell.tip2Label.text = quality_localized_name
        cell.tipLabel.textColor = (exterior_localized_name == "崭新出厂" ||  exterior_localized_name == "略有磨损") ? UIColor(hex: "#7EB173") :  exterior_localized_name == "久经沙场" ? UIColor(hex: "#7EB173") :   exterior_localized_name == "战痕累累" ? UIColor(hex: "#D9584D")   : rarity == "非凡" ? UIColor(hex: "#D9584D")   : rarity == "卓越" ? UIColor(hex: "#947DDD") : .white
        cell.tip2Label.textColor = quality_localized_name == "纪念品" ? UIColor(hex: "#EAE098") :  (quality_localized_name == "★ StatTrak™" || quality_localized_name == "★") ?  UIColor(hex: "#947DDD") : UIColor(hex: "#947DDD")
        cell.tipWidthConstraints.constant = exterior_localized_name?.count == 4 ? 56 : (exterior_localized_name?.count == 2 || rarity?.count == 2) ? 35 : 0
        cell.tip2WidthConstraints.constant = quality_localized_name?.count == 3 ? 40 : exterior_localized_name?.count == 2 ? 40 : quality_localized_name?.count == 1 ? 20 : 0
        cell.tip1View.backgroundColor = (cell.tipLabel.text == "崭新出厂" || cell.tipLabel.text == "略有磨损"  || cell.tipLabel.text == "久经沙场" || cell.tipLabel.text == "战痕累累" || cell.tipLabel.text == "非凡") ? UIColor(hex: "#D9584D")  : cell.tipLabel.text == "卓越" ? UIColor(hex: "#947DDD") : UIColor(hex: "#D9584D")
    
        return cell
    }
    

    public lazy var collectionView: UICollectionView = {
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize.init(width: (KScreenWidth-30)/2, height: 150)
        layout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 10
        layout.scrollDirection = .vertical
        
        let collectionView: UICollectionView = UICollectionView(frame:.zero, collectionViewLayout: layout)
//        collectionView.showsHorizontalScrollIndicator = false
//        collectionView.showsVerticalScrollIndicator = false
        collectionView.backgroundColor = UIColor.clear
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(UINib(nibName: "dataCollectionCell", bundle: nil), forCellWithReuseIdentifier: "dataCollectionCell")
        return collectionView
    }()
    
    func hud(){
        var hud = MBProgressHUD.showAdded(to: self.view, animated: true)
        hud.tintColor = .white
        hud.contentColor = .white
        hud.bezelView.style = .solidColor;
        hud.bezelView.backgroundColor = .black
        hud.mode = MBProgressHUDMode.text
        hud.label.text = "365天0小时后可交易\n"
    //延迟隐藏
        hud.hide(animated: true, afterDelay:1)
    }

    var page:Int = 1
    var pageSize:Int = 60
    var list:[JSON] = []
    func getData(){
        print(page)
        if(page >= 5){
            self.collectionView.mj_footer?.endRefreshingWithNoMoreData()
            return
        }
        let pageName = "page\(page)"
        if let path = Bundle.main.path(forResource: pageName, ofType: "json"){
            if let data = NSData(contentsOfFile: path) as? Data{
                if let json = try?JSONSerialization.jsonObject(with: data , options: .mutableContainers){
                    let parseJson = JSON(json)
                    if let items = parseJson["data"]["items"].array{
                        list.append(contentsOf: items)
                        self.collectionView.reloadData()
                        self.collectionView.mj_footer?.endRefreshing()
                        self.collectionView.mj_header?.endRefreshing()
                        if (page == 1){
                            hud()
                        }
                    }
               }
            }
        }
    }
    
    @objc func getDefalutData(){
        self.page = 1
        self.list.removeAll()
        self.getData()
    }
    
    @objc func getMoreData(){
        page += 1;
        self.getData()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        
        self.view.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(128)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(-KUITabBarHeight)
        }
        let refreshFooter = MJRefreshAutoNormalFooter.init(refreshingTarget: self, refreshingAction:#selector(getMoreData))
        let refreshHeader = MJRefreshStateHeader.init(refreshingTarget: self, refreshingAction:#selector(getDefalutData))
        refreshHeader.setTitle("件数: 807 估值: ￥4928000.67", for: .pulling)
        refreshHeader.setTitle("件数: 807 估值: ￥4928000.67", for: .refreshing)
        refreshHeader.setTitle("件数: 807 估值: ￥4928000.67", for: .willRefresh)
        refreshHeader.lastUpdatedTimeLabel?.text = ""
        self.collectionView.mj_footer = refreshFooter
        self.collectionView.mj_header = refreshHeader

        getDefalutData()
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
